package com.xinpan.exercise;
/*
 * Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.
 */
public class ReverseLinkedList2 {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ListNode newH = new ListNode(-1);
        newH.next = head;
        
        ListNode pre = newH;
        ListNode cur = pre.next;
        for(int i = 1; i < m; i++)
        {
            pre = cur;
            cur = cur.next;
        }
        
        ListNode tail = cur;
        ListNode next = cur.next;
        ListNode h = null;
        for(int i = m; i < n; i++)
        {
            h = next.next;
            next.next = cur;
            cur = next;
            next = h;
        }
        tail.next = next;
        pre.next = cur;
        
        return newH.next;
    }
}
